package com.pg_chat.controller;

import com.alibaba.fastjson.JSONObject;
import com.pg_chat.config.MsgConfig;
import com.pg_chat.model.Constant;
import com.pg_chat.model.FriendsEntity;
import com.pg_chat.model.UserEntity;
import com.pg_chat.model.VO.UserInfoVO;
import com.pg_chat.service.FriendsService;
import com.pg_chat.service.UserService;
import com.pg_chat.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController("chatServiceController")
public class ChatServiceController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserService userService;

    @Resource
    private FriendsService friendsService;

    private UserEntity user;

    private void userAuth(HttpSession session){
        user =
                (UserEntity) session.getAttribute(Constant.GLOBAL_USER);
    }

    /**
     * 首页
     * @param request 请求
     * @param session session
     * @return page
     */
    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request, HttpSession session){
        userAuth(session);

        ModelAndView mv = new ModelAndView("pages/index");
        String account = user.getUsername();
        mv.addObject("userId",user.getUserId())
                .addObject("username",account);
        return mv;

    }

    /**
     * 根据账号id获取用户信息
     * @param account 账号id
     * @return 用户信息
     */
    @RequestMapping("/userInfo")
    public String userInfo(String account){
        MsgConfig<JSONObject> msgConfig = new MsgConfig<>();
        UserInfoVO info;
        JSONObject json;
        msgConfig.fMsg("获取用户信息失败");
        String result = JsonUtil.resultMsgStr(msgConfig);
        if(account == null || "".equals(account)){
            return result;
        }

        UserEntity userInfo = user;
        String userId = String.valueOf(user.getUserId());
        if(!userId.equals(account))
            try{
                userInfo = userService.userMsg(account);

            }catch (Exception e){
                return result;
            }
        info = UserInfoVO.exchange(userInfo);
        json = (JSONObject) JSONObject.toJSON(info);
        msgConfig.sucMsg(json,"获取成功");
        result = JsonUtil.resultMsgStr(msgConfig);
        return result;
    }


    /**
     * 获取好友信息列表
     * @param userId 用户id
     * @return 好友列表
     */
    @RequestMapping("/friendsList")
    public String friList(String userId){
        String result;
        MsgConfig<JSONObject> msgConf = new MsgConfig<>();
        msgConf.fMsg("获取失败");
        try{
            JSONObject data = friendsService
                    .friendsList(userId);
            if(data != null)
                msgConf.sucMsg(data,"成功");
            return JsonUtil.resultMsgStr(msgConf);
        }catch (Exception e){
            msgConf.fMsg("失败");
            logger.error("error",e);
        }

        return JsonUtil.resultMsgStr(msgConf);
    }

    /**
     * 添加好友
     * @param friends 好友列<备注，好友实体>
     * @return json
     */
    @RequestMapping("addFriends")
    public String friAdd(@RequestBody
                         List<Map<String,FriendsEntity>>
                         friends){
        MsgConfig<Boolean> msgCfg = new MsgConfig<>();
        msgCfg.fMsg("添加失败");
        try{
            Boolean isSuccess = friendsService
                    .addFriends(friends);
            if(isSuccess)
                msgCfg.sucMsg(true,"ok");
        }catch (Exception e){
            msgCfg.fMsg("异常错误");
            logger.error("error",e);
        }

        return JsonUtil.resultMsgStr(msgCfg);
    }

    /**
     * 删除好友
     * @param friends 好友列<备注，好友实体>
     * @return json
     */
    @RequestMapping("/deleteFriends")
    public String friDelete(@RequestBody
                                 List<Map<String,FriendsEntity>>
                                 friends){
        MsgConfig<Boolean> msgCfg = new MsgConfig<>();
        msgCfg.fMsg("添加失败");
        try{
            Boolean isSuccess = friendsService
                    .deleteFriends(friends);
            if(isSuccess)
                msgCfg.sucMsg(true,"ok");
        }catch (Exception e){
            msgCfg.fMsg("异常错误");
            logger.error("error",e);
        }

        return JsonUtil.resultMsgStr(msgCfg);
    }

    /**
     * 删除好友
     * @param friends 好友列
     * @return json
     */
    @RequestMapping("/updateFriends")
    public String friUpdate(@RequestBody
                                    List<FriendsEntity>
                                    friends) {
        MsgConfig<Boolean> msgCfg = new MsgConfig<>();
        msgCfg.fMsg("添加失败");
        try {
            JSONObject result = friendsService
                    .updateFriends(friends);
            if("".equals(result.get("")))
                msgCfg.sucMsg(true, "ok");
        } catch (Exception e) {
            msgCfg.fMsg("异常错误");
            logger.error("error", e);
        }


        return JsonUtil.resultMsgStr(msgCfg);
    }
    @RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
    public String changeStatus(Integer status, HttpSession session){
        MsgConfig<Boolean> msgCfg = new MsgConfig<>();
        msgCfg.fMsg("修改失败");
        try {
            UserEntity user = (UserEntity) session.getAttribute(Constant.GLOBAL_USER);
            user.setUserState(status);
            boolean isSuccess = userService.updateUserInfo(user);
            if(isSuccess) {
                msgCfg.sucMsg(true, "ok");
                session.setAttribute(Constant.GLOBAL_USER, user);
            }
        } catch (Exception e){
            msgCfg.fMsg("异常错误");
            logger.error("error", e);
        }
        return JsonUtil.resultMsgStr(msgCfg);
    }
}
